/*
 *    Copyright 2008-2009 The PoCo Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.asemantics.poco.serializer.xml;

import java.io.Writer;
import java.util.Stack;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import com.asemantics.poco.serializer.AbstractPoCoSerializer;
import com.asemantics.poco.serializer.PoCoSerializerException;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: XmlPoCoSerializer.java 272 2009-12-21 12:01:38Z simone.tripodi@gmail.com $
 */
public final class XmlPoCoSerializer extends AbstractPoCoSerializer {

    private final static String RESPONSE = "response";

    private final static String DEFAULT_ENCODING = "UTF-8";

    private final static String EMPTY = "";

    private final static String PRETTY_PRINT_ON = "yes";

    private final static SAXTransformerFactory FACTORY = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    private final AttributesImpl attributes = new AttributesImpl();

    private TransformerHandler transformerHandler;

    private final Stack<String> elements = new Stack<String>();

    public XmlPoCoSerializer(Writer writer, boolean prettyPrint) {
        super(writer, prettyPrint);
    }

    public XmlPoCoSerializer(Writer writer) {
        super(writer);
    }

    /**
     * 
     * @param outputStream
     * @param prettyPrint
     */
    public void init(Writer writer, boolean prettyPrint) {
        try {
            this.transformerHandler = FACTORY.newTransformerHandler();

            Transformer transformer = this.transformerHandler.getTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);

            if (prettyPrint) {
                transformer.setOutputProperty(OutputKeys.INDENT, PRETTY_PRINT_ON);
            }

            this.transformerHandler.setResult(new StreamResult(writer));
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void startDocument() throws PoCoSerializerException {
        try {
            this.transformerHandler.startDocument();
        } catch (SAXException e) {
            throw new PoCoSerializerException(e);
        }

        this.elements.push(RESPONSE);
    }

    @Override
    protected void startObject() throws PoCoSerializerException {
        this.startXmlElement(this.elements.peek());
    }

    @Override
    protected void endObject() throws PoCoSerializerException {
        this.endXmlElement(this.elements.peek());
    }

    @Override
    protected void startList() throws PoCoSerializerException {
        // not used in XML
    }

    @Override
    protected void endList() throws PoCoSerializerException {
        // not used in XML
    }

    @Override
    protected void startElement(String name) throws PoCoSerializerException {
        this.elements.push(name);
    }

    @Override
    protected void endElement() throws PoCoSerializerException {
        this.elements.pop();
    }

    @Override
    protected void value(String text, boolean literal)
            throws PoCoSerializerException {
        String name = this.elements.peek();
        this.startXmlElement(name);

        try {
            this.transformerHandler.characters(text.toCharArray(), 0, text.length());
        } catch (SAXException e) {
            throw new PoCoSerializerException(e);
        }

        this.endXmlElement(name);
    }

    @Override
    protected void endDocument() throws PoCoSerializerException {
        try {
            this.transformerHandler.endDocument();
        } catch (SAXException e) {
            throw new PoCoSerializerException(e);
        }
    }

    //

    private void startXmlElement(String name) throws PoCoSerializerException {
        try {
            this.transformerHandler.startElement(EMPTY, name, name, this.attributes);
        } catch (SAXException e) {
            throw new PoCoSerializerException(e);
        }
    }

    private void endXmlElement(String name) throws PoCoSerializerException {
        try {
            this.transformerHandler.endElement(name, name, name);
        } catch (SAXException e) {
            throw new PoCoSerializerException(e);
        }
    }

}
